# -*- coding: utf-8 -*-
import os
from flask import request
from loguru import logger

def setup_logger(config):
    try:
        # 清空默认处理器
        # logger.remove()

        # 创建日志目录
        log_base_dir = config.get('LOG_DIR')
        if not os.path.exists(log_base_dir):
            os.makedirs(log_base_dir)

        # 按日期分文件夹，按小时进行文件落盘
        log_file_format = "{time:YYYY-MM-DD}/{time:YYYY-MM-DD_HH}.log"
        log_file = os.path.join(log_base_dir, log_file_format)

        # 配置文件日志
        logger.add(
            sink=log_file,
            level=config.get('LOG_LEVEL', 'INFO'),
            format="{time:YYYY-MM-DD HH:mm:ss} | {level: <8} | {name}:{function}:{line} - {message}",
            rotation="1 hour",  # 每小时滚动
            retention="30 days",  # 保留30天
            compression="gz",  # 压缩旧日志
            enqueue=True,  # 异步写入
            encoding="utf-8"
        )

        # 配置控制台日志
        logger.add(
            sink="stdout",
            level=config.get('LOG_LEVEL', 'INFO'),
            format="<green>{time:YYYY-MM-DD HH:mm:ss}</green> | <level>{level: <8}</level> | <cyan>{name}</cyan>:<cyan>{function}</cyan>:<cyan>{line}</cyan> - <level>{message}</level>",
            colorize=True,
        )

        # Flask请求日志中间件
        def before_request():
            logger.info(f"Request: {request.method} {request.path}")

        def after_request(response):
            logger.info(f"Response: {response.status}")
            return response
        return before_request, after_request
    except Exception as e:
        print(f"日志配置失败: {e}")
        return None, None